import React from 'react';
import { Modal, Form, Spin, Input, Select, Button, Table, Pagination, Switch, message } from 'antd';

import {
  PlusOutlined,
  SyncOutlined,
  CloseOutlined,
  CloseCircleOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import styles from './index.less';
import { connect } from 'dva';
const { Option } = Select;
const { Search } = Input;

import defaultSettings from '../../../../config/defaultSettings'

@Form.create()
@connect(({ system }) => ({ ...system }))
class RoleModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dateTime: '',
      checkColumns: [
        // { title: '序号', width: 80, render: (text, record, index) => `${index + 1}` },
        { title: '权限名称', dataIndex: 'authName', key: 'authName' },
        { title: '备注说明', dataIndex: 'remark', key: 'remark' },
        {
          title: '状态',
          dataIndex: 'statusCd',
          key: 'statusCd',
          render: (text, record) => (
            <span style={{ color: text == 1 ? 'green' : 'red' }}>
              {record.statusCdDesc}
            </span>
          ),
        },
        {
          title: '操作',
          dataIndex: 'cz',
          width: 100,
          render: (text, record) => record.statusCd==1?<Button size="small" onClick={(checked)=>this.editUserFun(false,record)}>删除</Button>:<Button type="primary" size="small" onClick={(checked)=>this.editUserFun(true,record)}>启用</Button>
          // <Switch defaultChecked onChange={(checked)=>this.editUserFun(checked,record)} />
          // render: (text, record) => record.statusCd == 2?<Switch checked={false} onChange={()=>this.editUserFun(record,1)} />:
            // <a style={{ fontSize: '12px' }} onClick={() => this.editUserFun(record,2)}>
            //   <CloseOutlined />
            //   删除
            // </a>,
        },
      ],
      authManList: [], //当前角色管理列表
      authLoading: false,
      pageSize: 10,
      currentPage: 1,
      totalData: 1,
      selectedRowKeys: [],
      selectedRows: [],
      systemNameList: [],
      currSystemId: '',
      currAuthName: '',
      currStaffId: ''
    };
  }

  componentDidMount(){
    this.init()
  }

  init = ()=>{
    this.querySystemNameList()
  }

  querySystemNameList = async () => {
    const { props } = this;
    await props
      .dispatch({
        type: 'system/systemNameListPost',
        payload: {
          page: 1,
          rows: 20,
        },
      })
      .then(res => {
        this.setState({
          systemNameList: res.list ? res.list : [],
          // currSystemId: res.list ? res.list[0].systemId : '',
          currSystemId: (defaultSettings.systemId&&defaultSettings.systemId!='')?defaultSettings.systemId: (res.list? res.list[0].systemId : '')
        });
        console.log(res, 'res');
      });
  };

  componentWillReceiveProps(nextProps){
    const { roleDetail } = nextProps;
    if(JSON.stringify(roleDetail)!='{}'){
      this.setState({
        currStaffId: roleDetail.staffId
      },()=>{
        this.queryRoleManSever();
      })
    }
  }

  //获取当前角色管理列表
  queryRoleManSever = () => {
    this.setState({
      authLoading: true,
    });
    const { props } = this;
    props
      .dispatch({
        type: 'system/queryRoleAuthList',
        payload: {
          systemId: this.state.currSystemId,
          objectId: this.props.roleDetail.roleId,
          authName: this.state.currAuthName
        },
      })
      .then(res => {
        let parents = res.filter(
          value => value.parentId == 0 || value.parentId == null
        );
        let childrens = res.filter(
          value => value.parentId !== 0 && value.parentId != null
        );
        for(let i=0;i<res.length;i++){
          res[i].key = res[i].authId
        }
        this.setState({
          authManList: res ? this.toTreeData(parents, childrens) : [],
          authLoading: false,
          totalData: res.total,
        });
        console.log(res, 'res22');
      });
  };

  fliterEvent= (parents, childrens) => {
    parents.forEach(parent => {
      childrens.forEach((current, index) => {
        if (current.parentId === parent.authId) {
          let temp = JSON.parse(JSON.stringify(childrens));
          temp.splice(index, 1);
          this.fliterEvent([current], temp);
          typeof parent.children !== "undefined"
            ? parent.children.push(current)
            : (parent.children = [current]);
        }
      });
    });
  };

  toTreeData = (parents,childrens)=>{
      this.fliterEvent(parents, childrens);
      return parents;
  }

  editUserFun = (checked, record) => {
    const { props } = this;
    props
      .dispatch({
        type: record.relId==-1?'system/editAdminUserRoleAuthPost':'system/editUserRoleAuthPost',
        payload: {
          objectId: this.props.roleDetail.roleId,
          relId: record.relId,
          authId: record.authId,
          systemId: this.state.currSystemId,
          objectType: 2,//角色
          statusCd: checked?1:2
        },
      })
      .then(res => {
        if(res.code == 0){
          message.success(checked?'启用成功！':'删除成功！')
        }else{
          message.error(checked?'启用失败！':'删除失败！')
        }
        this.setState({
          selectedRowKeys: []
        },()=>{
          this.queryRoleManSever()
        })
      });
  }

  handleCancel = e => {
    const { onCancel } = this.props;
    onCancel();
  };

  timeSelect = (value, dateString) => {
    this.setState({
      dateTime: dateString,
    });
  };

  //提交订单
  submitFun = value => {
    console.log(value, 'value');
    this.queryRoleManSever();
  };

  //重置
  resetFun = () => {
    this.setState(
      {
        currUsername: '',
        currOrgName: '',
        currTellphone: '',
        currStatus: '',
        currType: '',
        timestamp: Date.parse(new Date()) + 1,
      },
      () => {
        this.init();
      },
    );
  };

  //删除
  deleteData = record => {};

  onSelectChange = (selectedRowKeys,selectedRows) => {
    console.log(selectedRows, 'selectedRows');
    this.setState({ selectedRowKeys, selectedRows });
  };

  pageChange = page => {
    this.setState(
      {
        currentPage: page,
      },
      () => {
        this.queryRoleManSever();
      },
    );
  };

  systemChange = value => {
    this.setState({
      currSystemId: value
    });
  };

  authNameChange = e => {
    this.setState({
      currAuthName: e.target.value
    });
  };

  batUserFun = (status) => {
    const { props, state: { selectedRows } } = this;
    let ampStaffAuthList = [];
    for(let i=0;i<selectedRows.length;i++){
      const item = {
        objectId: this.props.roleDetail.roleId,
        relId: selectedRows[i].relId,
        authId: selectedRows[i].authId,
        systemId: this.state.currSystemId,
        objectType: 2,
        statusCd: status
      }
      ampStaffAuthList.push(item)
    }
    props
      .dispatch({
        // type: selectedRows[0].relId==-1?'system/batAdminUserRoleAuthPost':'system/batUserRoleAuthPost',
        type: 'system/batAdminUserRoleAuthPost',
        payload: ampStaffAuthList,
      })
      .then(res => {
        if(res.code == 0){
          message.success(status==1?'启用成功！':'禁用成功！')
        }else{
          message.error(status==1?'启用失败！':'禁用失败！')
        }
        this.setState({
          selectedRowKeys: []
        },()=>{
          this.queryRoleManSever()
        })
      });
  }

  render() {
    const { form, loading , ...roleModalProps } = this.props;
    const { systemNameList, authManList } = this.state;
    console.log( authManList )
    // const { getFieldDecorator } = form;
    // const formItemLayout = {
    //     labelCol: {
    //       xs: { span: 24 },
    //       sm: { span: 8 },
    //     },
    //     wrapperCol: {
    //       xs: { span: 24 },
    //       sm: { span: 16 },
    //     },
    // };
    const { checkColumns, authLoading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    
    return (
      <Modal {...roleModalProps} onCancel={this.handleCancel} footer={null}>
        <Spin spinning={loading}>
          <dl>
            <dt>
              <Form name="horizontal_search" layout="inline">
                {
                  (!defaultSettings.systemId||defaultSettings.systemId=='')&&
                  <Form.Item name="status" label="系统名称">
                    <Select
                        style={{ width: 150 }}
                        placeholder="请选择系统名称"
                        onChange={this.systemChange}
                        value={this.state.currSystemId}
                      >
                        <Option value="">全部</Option>
                        {
                          systemNameList.map(item=>{
                            return(<Option value={item.systemId}>{item.systemName}</Option>)
                          })
                        }
                      </Select>
                  </Form.Item>
                }
                <Form.Item>
                  <Search
                    placeholder="请输入名称搜索"
                    style={{ width: 200 }}
                    onChange={this.authNameChange}
                    onSearch={this.submitFun}
                    enterButton
                  />
                  <Button style={{ marginLeft: '8px' }} onClick={this.resetFun}>
                    <SyncOutlined />
                    重置
                  </Button>
                </Form.Item>
                <Form.Item style={{ float: 'right' }}>
                  <Button type="primary" style={{ marginRight: '5px' }} onClick={()=>this.batUserFun(1)} disabled={selectedRowKeys.length>0?false:true}>
                    <CheckCircleOutlined />
                    启用
                  </Button>
                  <Button onClick={()=>this.batUserFun(2)} disabled={selectedRowKeys.length>0?false:true}>
                    <CloseCircleOutlined />
                    禁用
                  </Button>
                </Form.Item>
              </Form>
            </dt>
            <dd>
              <Spin spinning={this.state.authLoading} delay={500}>
                <Table
                  style={{ marginTop: '20px' }}
                  bordered
                  columns={checkColumns}
                  dataSource={authManList}
                  // simple
                  scroll={{ y: 450 }}
                  pagination={false}
                  rowSelection={rowSelection}
                />
                {/* <Table rowSelection={rowSelection} columns={checkColumns} dataSource={authManList} /> */}
              </Spin>
              {/* <p style={{ textAlign: 'center', marginTop: '20px' }}>
                <Pagination
                  pageSize={this.state.pageSize}
                  current={this.state.currentPage}
                  total={this.state.totalData}
                  onChange={this.pageChange}
                />
              </p> */}
            </dd>
          </dl>
        </Spin>
      </Modal>
    );
  }
}

export default RoleModal;
